/*
 * Copyright 2025 RestfulToolX Contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.welson.restfultoolx.service;

import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.Service;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

/**
 * 搜索历史服务
 * 用于保存和管理搜索历史记录
 */
@Service
@State(
    name = "RestfulToolXSearchHistory",
    storages = @Storage("restfulToolXSearchHistory.xml")
)
public final class SearchHistoryService implements PersistentStateComponent<SearchHistoryService> {
    
    private static final int MAX_HISTORY_SIZE = 20;
    
    private String lastSearchQuery = "";
    private List<String> searchHistory = new ArrayList<>();
    
    /**
     * 获取上次搜索的查询字符串
     */
    public String getLastSearchQuery() {
        return lastSearchQuery != null ? lastSearchQuery : "";
    }
    
    /**
     * 保存搜索查询
     */
    public void saveSearchQuery(String query) {
        if (query == null || query.trim().isEmpty()) {
            return;
        }
        
        query = query.trim();
        this.lastSearchQuery = query;
        
        // 移除已存在的相同查询
        searchHistory.remove(query);
        
        // 添加到历史记录开头
        searchHistory.add(0, query);
        
        // 限制历史记录大小
        if (searchHistory.size() > MAX_HISTORY_SIZE) {
            searchHistory = searchHistory.subList(0, MAX_HISTORY_SIZE);
        }
    }
    
    /**
     * 获取搜索历史记录
     */
    public List<String> getSearchHistory() {
        return new ArrayList<>(searchHistory);
    }
    
    /**
     * 清空搜索历史
     */
    public void clearHistory() {
        searchHistory.clear();
        lastSearchQuery = "";
    }
    
    @Override
    public @Nullable SearchHistoryService getState() {
        return this;
    }
    
    @Override
    public void loadState(@NotNull SearchHistoryService state) {
        XmlSerializerUtil.copyBean(state, this);
    }
}